<?php

function logging($m) {
    echo $m . "\n";
}

function read($url, $data = null) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    if ($data != null) {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    $out = curl_exec($ch);
    curl_close($ch);
    return $out;
}

function upload($url, $filename) {
    $content = file_get_contents($filename);
    $content = base64_encode($content);
    $content = "data:file/zip;base64," . $content;
    $content = urlencode($content);
    $content = "data=" . $content;

    return read($url, $content);
}

$tmpdir = dirname(__FILE__) . "/temp";
if (!file_exists($tmpdir)) {
    mkdir($tmpdir, 0777, true);
}
if (!is_dir($tmpdir)) {
    die("no temp dir.");
}

$sock = new swoole_client(SWOOLE_SOCK_TCP);

if (!$sock->connect("10.18.203.47", 10123, -1)) {
    exit("connect failed. Error: {$sock->errCode}\n");
}

$register = array("op" => "register", "data" => array("title" => "UiAutomator Viewer", "name" => "uiautomator", "info" => "请将截屏文件(uiautomator.png)和xml文件(uiautomator.xml)打包成tgz文件并上传"));
$sock->send(json_encode($register));

while (true) {
    $ret = $sock->recv();
    if (empty($ret)) {
        logging("Server down.");
        break;
    }
    var_dump($ret);
    $ret = json_decode($ret, true);

    $op = $ret["op"];
    $data = $ret["data"];
    if ($op == "task") {
        $taskid = $data["id"];
        $url = $data["file"];
        $uploadurl = $data["upload"];
        $failurl = $data["fail"];

        $content = file_get_contents($url);
        $tgzfile = $tmpdir . "/uiautomator.tgz";
        file_put_contents($tgzfile, $content);

        // ---------------------------------------------------------
        $command = dirname(__FILE__) . "/make.sh";
        logging($command);
        $fp = popen($command, "r");
        while (!feof($fp)) {
            $s = fgets($fp);
            logging($s);
        }
        pclose($fp);

        $result = $tmpdir . "/result.zip";
        if (file_exists($result)) {
            $url = $uploadurl . "&task=" . $taskid . "&post=unzip&entry=index.html";
            logging($url);
            $ret = upload($url, $result);
            var_dump($ret);
        } else {
            $ret = read($failurl . "&task=" . $taskid);
            var_dump($ret);
        }

        // ---------------------------------------------------------

        $result = array(
            "op" => "task", 
            "data" => array(
                "id" => $taskid,
            ),
        );
        $sock->send(json_encode($result));
    }
}

$sock->close();


